<template>
  <el-dialog v-model="dialogVisible" title="选择维修工" width="30%">
    <el-form :model="form">
      <el-form-item label="选择维修工" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择维修工">
          <el-option
              v-for="worker in workers"
              :key="worker.roleId"
              :label="worker.roleName"
              :value="worker.roleId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="WorkerDialog">
import { ref, defineExpose, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import {putObj,getWorkerList} from "/@/api/repair/propertyRepair";

// 在 script setup 中添加类型定义
interface Worker {
  roleId: string;
  roleName: string;
}
const dialogVisible = ref(false);
const workers = ref<Worker[]>([]);
const form = reactive({
  roleId: '',
  repairId: '',
  worker: '',
  status: 1,
});

const loadWorkerList = async () => {
  const res = await getWorkerList();
  workers.value = res.data;
};
const emit = defineEmits(['refresh']);
const handleSave = async () => {
  // 检查是否选择了维修工
  if (!form.roleId) {
    ElMessage.warning('请选择维修工');
    return;
  }
  // 通过 roleId 在 workers 数组中查找对应的 roleName
  const selectedWorker = workers.value.find(worker => worker.roleId === form.roleId);
  if (selectedWorker) {
    // 将 roleName 赋值给 form.workers
    form.worker = selectedWorker.roleName;
    try {
      // 提交包含正确数据的表单
      await putObj(form);
      dialogVisible.value = false;
      ElMessage.success('指派成功');
    } catch (error) {
      ElMessage.error('指派失败');
    }
  } else {
    ElMessage.warning('未找到选中的维修工信息');
  }
  emit('refresh');
};

const openDialog = (id:string) => {
  dialogVisible.value = true;
  form.roleId = '';
  loadWorkerList();
  form.repairId = id;
};

defineExpose({ openDialog });
</script>
